// var mqtt = require('../mqtt/dist/mqtt.js')
// import mqtt from "../mqtt/dist/mqtt.js";
// import mqtt from 'mqtt'
import * as mqtt from "../mqtt/dist/mqtt"
// import  mqtt from "../mqtt/dist/mqtt";
// 或者只引入需要的部分
export const socket = {
	ttMqtt: null,
	token: null,
	topicPush:"user/publish",
	topicUserRegister: "user/register/",
	topicUserLogin: "user/login/",
	topicUserSubscribe: "user/subscribe/",
	clientId: "",
	clientStatus: false,
	MQTT_IP: "192.168.1.134:8083/mqtt",
	MQTT_OPTIONS:{
		connectTimeout: 5000,
		clientId: "",
		username: "admin",
		password: "public",
		clean: true
	},
	init(url : string, token : string) {
		// socket.MQTT_IP = url;
		socket.token = token;
		//生成连接id
		socket.getClientId();
		
		socket.connect();
	},
	connect(){
		// #ifdef H5
		socket.ttMqtt = mqtt.connect('ws://' + socket.MQTT_IP, socket.MQTT_OPTIONS)
		// #endif
		// #ifdef MP-WEIXIN||APP-PLUS
		socket.ttMqtt = mqtt.connect('wx://' + socket.MQTT_IP, socket.MQTT_OPTIONS)
		// #endif
		
		//连接
		socket.ttMqtt.on('connect', function() {
			uni.showToast({
				title: "连接成功",
				icon: "none"
			})
			console.log('连接成功');
			uni.hideLoading();
			socket.clientStatus = true;
			
			socket.subscribe(socket.topicUserRegister);
			socket.subscribe(socket.topicUserLogin);
			
			//发布注册消息
			socket.send(JSON.stringify({
				type: 'userRegister',
				token: socket.token
			}));
		});
		
		socket.ttMqtt.on('message', function(topic, message) {
			if(topic == socket.topicUserRegister){
				var data = JSON.parse(message);
				var topic_subscribe = socket.topicUserSubscribe + data.data;
				
				socket.subscribe(topic_subscribe);
				return true;
			}
			
			uni.$emit('receivedMsgCallBack', message)
			// console.log("message: ")
			// console.log(message)
			// console.log('接收推送信息：', message.toString())
		})
		
		//重连
		socket.ttMqtt.on('reconnect', function(error){
			uni.getNetworkType({
				success: function(res) {
					console.log(res.networkType); //网络类型 wifi、2g、3g、4g、ethernet、unknown、none
					if (res.networkType === "none") {
						console.log("当前无网络");
						socket.ttMqtt.end();
					} else {
						console.log("有网络");
						uni.showToast({
							title: "正在重连...",
							icon: "none"
						})
						uni.showLoading({
							title: 'Loading...'
						});
					}
				}
			})
		});
		socket.ttMqtt.on('offline', (msg) => {
			console.log('掉线', msg);
			uni.showToast({
				title: '掉线',
				icon: 'none',
			})
		});
		
		socket.ttMqtt.on('error', function(error) {
			console.log('连接失败...', error);
			uni.showToast({
				title: "连接失败...",
				icon: "none"
			})
			uni.hideLoading();
		});
		socket.ttMqtt.on('end', function() {
			console.log('连接断开')
			uni.showToast({
				title: "连接断开",
				icon: "none"
			})
			uni.hideLoading();
			socket.ttMqtt = {};
			socket.clientStatus = false;
		});
		
		
	},
	subscribe(topic){
		if (!socket.clientStatus) {
			uni.showToast({
				title: "请连接",
				icon: "none"
			})
			return;
		}
		socket.ttMqtt.subscribe(topic, function(err) {
			if (!err) {
				console.log('订阅成功');
				uni.showToast({
					title: "订阅成功",
					icon: "none"
				})
			}
		})
	},
	send(data){
		var dataObject = JSON.parse(data);
		dataObject.token = socket.token;
		dataObject.clientId = socket.clientId;
		
		var DataValue = JSON.stringify(dataObject);
		var topic = socket.topicPush;
		socket.ttMqtt.publish(topic, DataValue, {}, function(err) {
			if (!err) {
				console.log('发送成功');
				uni.showToast({
					title: "发送成功",
					icon: "none"
				})
			}
		});
	},
	end(){
		socket.ttMqtt.connected = false;// 移动端不加这个关闭回调不会触发
		socket.ttMqtt.end(true, (err) => {
			if (err) {
				socket.ttMqtt.connected = true;
			} else {
				console.log('断开成功')
			}
		});
	},
	getClientId(){
		var randomNum = Math.floor(Math.random() * 101);
		var random = randomNum.toString();
		let time = new Date().getTime();
		var clientId = time.toString() + random;
		
		//初始化连接id
		socket.MQTT_OPTIONS.clientId = time.toString() + random;
		socket.clientId = clientId.toString() + random;
		
		//初始化注册订阅主题
		socket.topicUserRegister = socket.topicUserRegister + clientId;
		
		//初始化登录订阅主题
		socket.topicUserLogin = socket.topicUserLogin + clientId;
	}
}